package com.jackrain.nea.fc.dl.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jackrain.nea.common.*;
import com.jackrain.nea.dl.common.utils.esutil.ConvertQueryListUtil;
import com.jackrain.nea.dl.common.utils.esutil.ElasticsearchUtil;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.dl.api.WmsTranOutBoxSaveCmd;
import com.jackrain.nea.fc.dl.mapper.WmsTranMapper;
import com.jackrain.nea.fc.utils.Constants;
import com.jackrain.nea.fc.utils.UserInformation;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.RuntimeCompute;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.query.DefaultWebEvent;
import com.jackrain.nea.web.query.QuerySessionImpl;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.HashMap;
/**
 * 调拨出库回传 拣货装箱-->发出
 * @author zhang.zz
 * @date 2018/10/24
 * hhh
 */
@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "dl")
public class WmsTranOutBoxSaveCmdImpl extends CommandAdapter implements WmsTranOutBoxSaveCmd {


    @Autowired
    PostDubbleEvent postDubbleEvent;
    @Autowired
    PostHandleEvent postHandleEvent;
    @Autowired
    QueryCpUtil postQueryEvemt;
    @Autowired
    QueryUserUtil postUserEvent;


    @Autowired
    private ElasticsearchUtil esUtil;

    @Autowired
    private ConvertQueryListUtil convertQLUtil;

    @Autowired
    private BtranEsName btranEsName;

    private Logger accesLogger = LoggerFactory.getLogger(Constants.ACCESS_PARAM_LOGGER);

    @Override
    public ValueHolder execute(HashMap map) throws NDSException {

        ValueHolder vh = new ValueHolder();
        WmsTranMapper wmsTranMapper = ApplicationContextHandle.getBean(WmsTranMapper.class);

        JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(map.get("param"), "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
        if (null == param || param.size() == 0) {
            throw new NDSException("参数格式错误！");
        }
        log.info("WmsTranOutBoxSaveCmdImpl-->param-->{}",param);
//        log.debug("----------拣货回传（拣货装箱单）----------" + param);
        RuntimeCompute runtimeCompute = ApplicationContextHandle.getBean("runtimeCompute");
        runtimeCompute.startRuntime();
        JSONArray dataArray = param.getJSONArray("data");
        JSONArray succesIdArray = new JSONArray();
        JSONArray errArray = new JSONArray();
        JSONArray queryDataArray = new JSONArray();

        for (int i = 0; i < dataArray.size(); i++) {

            JSONArray jsonArray = dataArray.getJSONArray(i);
            JSONArray bill_no_jsonarray = jsonArray.getJSONArray(0);
            String wms_bill_no = jsonArray.getString(1);
            Long objid = jsonArray.getLong(2);
            //传输数据
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("TranIDs", bill_no_jsonarray);
            jsonObject.put("WMSNO", wms_bill_no);
            try {
                User user = postUserEvent.getUser(UserInformation.USER_NAME);
                String notic = "com.jackrain.nea.dl.tran.api.BtranboxByWmsCmd:1.0:dl";
                QuerySessionImpl querySession = new QuerySessionImpl(user);
                DefaultWebEvent event = new DefaultWebEvent("dlOrderOut", new HashMap(16));
                event.put("param", jsonObject);
                querySession.setEvent(event);
                accesLogger.info("WmsTranOutBoxSaveCmdImpl--jsonObject-->{}",jsonObject);
//                log.debug("-------拣货装箱参数------->" + jsonObject);
                if( objid==null || objid < 0){
                        //1.生成拣货装箱单
                    JSONObject retJo = postDubbleEvent.executePostDubble(notic, querySession);
                    accesLogger.info("WmsTranOutBoxSaveCmdImpl--retJo-->{}",retJo);
//                    log.debug("----------拣货装箱保存 回传----------" + retJo);
                    if (retJo.get("code") != null && (int) retJo.get("code") < 0) {
                        throw new NDSException("生成拣货单失败:" + retJo.get("message") + retJo.get("error") + retJo.get("data"));
                    }
                    JSONObject data = retJo.getJSONObject("data");
                    objid = data.getLong("objid");
                }
                queryDataArray.add(jsonObject);
//                log.debug("----------拣货装箱发出----------");
                //2.发出服务
                JSONObject resultJson = new JSONObject();
                resultJson.put("objid", objid);
                resultJson.put("isWMSCheck", "N");
                accesLogger.info("WmsTranOutBoxSaveCmdImpl--resultJson-->{}",resultJson);
//                resultJson.put("STORE_DATE", dateToStrLong(oldJo.getDate("DATE_OUT")));
//                log.info("发出resultJson==>" + resultJson.toString());
                event.put("param", resultJson);
                event.setParameter("command", "com.jackrain.nea.dl.tran.api.BtranboxSendCmd:1.0:dl");
                event.setParameter("table", "DL_B_TRAN_BOX");
                event.setParameter("webaction", "BOX_SEND_STATUS_SINGLE");
                querySession.setEvent(event);
                JSONObject subJo = postHandleEvent.executePostHandle(resultJson, querySession, event, "webaction");
                accesLogger.info("WmsTranOutBoxSaveCmdImpl--subJo-->{}",subJo);
//                log.debug("----------拣货装箱发出 回传----------" + subJo);
                if (subJo.get("code") != null && (int) subJo.get("code") < 0) {
                    throw new NDSException("发出失败:" + subJo.get("message") + subJo.get("error") + subJo.get("data"));
                }
                HashMap hashMap = new HashMap();
                hashMap.put("wms_bill_no",wms_bill_no);
                hashMap.put("objid",objid);
                JSONObject obj = new JSONObject(hashMap);
                succesIdArray.add(obj);
            } catch (Exception e) {
                JSONObject errrobj = new JSONObject();
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                e.printStackTrace(pw);
                if (e instanceof NDSException) {
                    errrobj.put("message", e.getMessage());
                } else {
                    errrobj.put("message", sw.toString());
                }
                errrobj.put("key", wms_bill_no);
                errArray.add(errrobj);
            }

        }

        if (errArray.size() > 0) {
            vh.put("error", errArray);
            vh.put("successIds", succesIdArray);
            vh.put("code", -1);
        } else {
            vh.put("successIds", succesIdArray);
            vh.put("code", 0);
        }
        vh.put("queryDataArray",queryDataArray);
        Double spendTime = runtimeCompute.endRuntime();
        vh.put("spendtime", spendTime);
//        log.debug("---------拣货装箱单执行时间--------->>" + spendTime);

        return vh;

    }
    /**
     * 将长时间格式时间转换为字符串 yyyy-MM-dd HH:mm:ss
     *
     * @param dateDate
     * @return
     */
    public static String dateToStrLong(java.util.Date dateDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String dateString = formatter.format(dateDate);
        return dateString;
    }


}